package com.example.musicapp.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.example.musicapp.application.MyApp;
import com.example.musicapp.network.HttpResponseListener;

import org.json.JSONException;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import static com.example.musicapp.application.MyApp.getThreadPool;
import static com.example.musicapp.application.MyApp.sJSessionId;
import static com.example.musicapp.application.MyApp.sThreadPool;


public class HttpUtils {
    private static final long CONNECT_TIMEOUT = 10;
    private static final long READ_TIMEOUT = 10;
    private static final long WRITE_TIMEOUT = 10;

    public static void sendOkHttpRequest(String address, okhttp3.Callback callback) {
        MyApp.getThreadPool().execute(() -> {
            OkHttpClient client = new OkHttpClient.Builder()
                    //连接超时
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                    //读取超时
                    .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                    //写超时
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS).build();
            Request request = new Request.Builder()


                    .url(address)
                    .build();
            client.newCall(request).enqueue(callback);
        });
    }


    public static void sendPostOkRequest(String address, RequestBody body, okhttp3.Callback callback) {
        MyApp.getThreadPool().execute(() -> {
            OkHttpClient client = new OkHttpClient.Builder()
                    //连接超时
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                    //读取超时
                    .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                    //写超时
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS).build();
            Request request = new Request.Builder()
                    .url(address)
                    .post(body)
                    .build();
            client.newCall(request).enqueue(callback);
        });
    }

    /**
     * 是否有进行网络连接
     *
     * @param context 上下文
     * @return 是否
     */
    public static boolean isConn(Context context) {
        boolean bisConnFlag = false;
        ConnectivityManager conManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo network = conManager.getActiveNetworkInfo();
        if (network != null) {
            bisConnFlag = conManager.getActiveNetworkInfo().isAvailable();
        }
        return bisConnFlag;
    }


    public static void sendHttpRequest(final String address, final HttpResponseListener listener) {
        getThreadPool().execute(() -> {
            HttpURLConnection conn = null;
            BufferedReader br = null;
            try {
                InputStream in = getHttpInputStream(conn, br, address);
                br = new BufferedReader(new InputStreamReader(in));
                String line;
                StringBuffer response = new StringBuffer();
                while ((line = br.readLine()) != null) {
                    response.append(line);
                }
                if (listener != null) {
                    listener.onSuccess(response.toString());
                }
            } catch (Exception e) {
                if (listener != null) {
                    listener.onFailure(e, 1);
                }
            } finally {
                if (br != null) {
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (conn != null) {
                    conn.disconnect();
                }
            }
        });

    }

    public static void sendHttpNoThread(final String address, final HttpResponseListener listener) {
        HttpURLConnection conn = null;
        BufferedReader br = null;
        try {
            InputStream in = getHttpInputStream(conn, br, address);
            br = new BufferedReader(new InputStreamReader(in));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            if (listener != null) {
                listener.onSuccess(response.toString());
            }
        } catch (Exception e) {
            if (listener != null) {
                listener.onFailure(e, 1);
            }
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }

    }

    /**
     * @param conn    HttpURLConnection
     * @param br      BufferedReader
     * @param address 地址字符串
     * @return 获取到的比特流
     * @throws IOException io异常
     */
    public static InputStream getHttpInputStream(HttpURLConnection conn, BufferedReader br, String address) throws IOException {

        URL url = new URL(address);
        conn = (HttpURLConnection) url.openConnection();
        System.out.println("我要这个啊"+sJSessionId);
        conn.setRequestProperty("Cookie", sJSessionId);
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(8000);
        conn.setReadTimeout(8000);
        InputStream in = conn.getInputStream();

        return in;
    }

    /**
     * post方法
     */
    public static void sendPostData(String strUrlPath, Map<String, String> params, String encode, final HttpResponseListener listener) {
        sendPostData(strUrlPath, params, new HashMap<>(), encode, listener);
    }


    /**
     * Function  :   发送Post请求到服务器
     * Param     :   params请求体内容，encode编码格式
     */
    public static void sendPostData(String strUrlPath, Map<String, String> params, Map<String, String> headers, String encode, final HttpResponseListener listener) {
        getThreadPool().execute(() -> {
            {
                byte[] data;
                if (!params.isEmpty()) {
                    data = getRequestData(params, encode).toString().getBytes();
                } else {
                    data = strUrlPath.getBytes();
                }
                //获得请求体
                try {
                    URL url = new URL(strUrlPath);

                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setConnectTimeout(3000);
                    httpURLConnection.setDoInput(true);
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setRequestProperty("Cookie", sJSessionId);
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setUseCaches(false);
                    if (headers != null) {
                        for (String header : headers.keySet()) {
                            httpURLConnection.setRequestProperty(header, headers.get(header));
                        }
                    }
                    //设置请求体的类型是文本类型
                    httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");


                    //设置请求体的长度
                    httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));

                    //获得输出流，向服务器写入数据
                    OutputStream outputStream = httpURLConnection.getOutputStream();
                    outputStream.write(data);

/*                    Map<String, List<String>> response_headers = httpURLConnection.getHeaderFields();
                    System.out.println(response_headers+ "看看这货失是啥");
                    String jSessionId = null;
                    String cookie = "";
                    for (String key : response_headers.keySet()) {

                        if (key != null && "Set-Cookie".equals(key)) {
                            List<String> string = response_headers.get(key);

                            StringBuilder builder = new StringBuilder();
                            for (String str : string) {
                                System.err.println(str);
                                builder.append(str).toString();
                            }
                            cookie = builder.toString();
                            String[] jSessionIdArray = cookie.split(";", 0);

                            sJSessionId = jSessionIdArray[0];
                            System.out.println(sJSessionId + "看看这jession是啥"
                            );

                        }
                    }*/
                    //获得服务器的响应码
                    int response = httpURLConnection.getResponseCode();
                    if (response == HttpURLConnection.HTTP_OK) {
                        InputStream inputStream = httpURLConnection.getInputStream();
                        String responseStr = dealResponseResult(inputStream);
                        System.out.println("我是回应" + responseStr);
                        if (listener != null) {
                            listener.onSuccess(responseStr);
/*
                            listener.onFailure(responseStr, jSessionId);
*/
                        }
                    }
                } catch (IOException | JSONException e) {
                    if (listener != null) {
                        listener.onFailure(e, 1);
                    }
                }
            }
        });


    }

    /**
     * :   封装请求体信息
     * Param     :   params请求体内容，encode编码格式
     */
    public static StringBuffer getRequestData(Map<String, String> params, String encode) {
        StringBuffer stringBuffer = new StringBuffer();
        //存储封装好的请求体信息
        try {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                stringBuffer.append(entry.getKey())
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), encode))
                        .append("&");
            }
            //删除最后的一个"&"
            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer;
    }

    /**
     * Function  :   处理服务器的响应结果（将输入流转化成字符串）
     * Param     :   inputStream服务器的响应输入流
     */
    public static String dealResponseResult(InputStream inputStream) {
        //存储处理结果
        String resultData = null;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        try {
            while ((len = inputStream.read(data)) != -1) {
                byteArrayOutputStream.write(data, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        resultData = new String(byteArrayOutputStream.toByteArray());
        return resultData;
    }


    /**
     * 获取网落图片资源
     *
     * @param url
     * @return
     */
    public static Bitmap getHttpBitmap(String url) {
        Bitmap bitmap = null;
        HttpURLConnection conn = null;
        BufferedReader bufferedReader = null;
        try {
            //得到数据流
            InputStream is = getHttpInputStream(conn, bufferedReader, url);
            //解析得到图片
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }


}



